chrome拦截window.open弹窗问题的两种解决方式

您所在的位置:网站首页 chrome 弹窗显示为标签页 chrome拦截window.open弹窗问题的两种解决方式

chrome拦截window.open弹窗问题的两种解决方式

2024-02-01 00:31| 来源: 网络整理| 查看: 265

chrome拦截弹窗问题的两种解决方式

在前端编写中,可能会用到window.open,等方式来在新的tab打开url。但会发现,有些情况下新打开的tab页会被chrome拦截了:

chrome拦截

出现这种情况,很有可能是因为:这些调用不是由用户行为(如:点击)触发的。

一种典型场景就是:点击按钮,触发ajax请求,然后在ajax的回调中,打开新的tab页。这里,打开新tab页的操作是在回调的上下文中,并不在点击事件中,尝试打开tab页就会被拦截。

以ajax导出pdf文件为例,

$("#export_button").click(function(){ ... $.ajax({ url : 'generateExportPdfFileURl', ...... success : function(pdfFileUrl) { openInNewTab(pdfFileUrl); } ...... }); }); /*openInNewTab原始实现:被拦截*/ var openInNewTab = function(url) { var a = document.createElement("a"); a.setAttribute("href", url); a.setAttribute("target", "testNewWindow"); document.body.appendChild(a); a.click(); }

下面介绍通过增加用户行为触发和打开-更新多步操作两种解决方法。

增加用户行为触发

ajax回调中打开新窗口被拦,是因为回调中上下文已不是用户行为了,因此,可以通过在回调增加用户提示,由用户点击确认触发打开url:

/*openInNewTab实现:增加用户行为触发*/ var openInNewTab = function(url) { MsgUtil.alertPrompt("导出文件已生成",function () { var a = document.createElement("a"); a.setAttribute("href", url); a.setAttribute("target", "testNewWindow"); document.body.appendChild(a); a.click(); }, "打开"); } //MsgUtil.alertPrmpt是自行实现的提示弹窗: // alertPrmpt({prompt_text}, {callbackFn}, {button_text}); 打开-更新多步操作

ajax回调中打开新窗口被拦,是因为回调中上下文已不是用户行为了,另一种思路分步完成:在ajax之前打开一个新的window,然后在回调中更新window的location:

$("#export_button").click(function(){ ... openInNewTab("about:blank"); //先打开新窗口 $.ajax({ url : 'generateExportPdfFileURl', ...... success : function(pdfFileUrl) { updateNewWindowUrl(pdfFileUrl); } ...... }); }); //更新已打开窗口的url function updateNewWindowUrl(url) { var newWindow = window.open(null, 'testNewWindow'); newWindow.location.href = url; }

以上是以click为例验证两种方法,对于window.open打开新窗口,同理。

*:将ajax设置成同步调用,应该也可以,但不推荐。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3